import { message } from 'antd';
import axios from 'axios';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import logo from '../components/logo.png';
import config from '../config';
import '../styles/Login.css';
import DateTimeDisplay from './DateTimeDisplay';
function Login() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();

  const handleSubmit = (event) => {
    event.preventDefault();
    axios.post(`${config.apiUrl}/admin/login`, {
      nickname: username,
      password: password,
    })
    .then(response => {
      if (response.data.code === 200) {
        message.success(response.data.msg);
        localStorage.setItem('token', response.data.data); // 存储令牌
        navigate('/home');
      } else {
        message.error('登录失败，请检查账号和密码');
      }
    })
    .catch(error => {
      message.error('登录请求失败');
      console.error('Error during login:', error);
    });
  };

  return (
    <div className="login-page" style={{ position: 'relative'}}>
      <div className="login-container">
        <DateTimeDisplay style={{ position: 'absolute', top: '0px', right: '0px' }} />  
        <div className="login-logo">
          <img src={logo} alt="Logo" />
          <h1>水生态环境监测</h1>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <input
              type="text"
              placeholder="用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </div>
          <div className="form-group">
            <input
              type="password"
              placeholder="密码"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          <button type="submit">立即登录</button>
        </form>
      </div>
      
    </div>
    
  );
}

export default Login;